//
//  StoreMapViewController.m
//  iFoundIt
//
//  Created by Navid Shariat on 4/05/10.
//  Copyright 2010 QUT. All rights reserved.
//

#import "StoreMapViewController.h"
#import "StoreListViewController.h";

@implementation StoreMapViewController

@synthesize foundPlaces;
@synthesize mapView;
@synthesize locationManager;	
@synthesize currentLocationCoordinate;	
@synthesize alternativeLocationCoordinate;

const NSString * mapViewCurrentLocationAnnotTitle=@"Your Location";
const NSString * mapViewStoreLocationAnnotTitle=@"Store Location";
const int mapViewCurrentLocColor= MKPinAnnotationColorPurple;
const int mapViewStoreLocColor= MKPinAnnotationColorRed;

- (void)dealloc {
	[foundPlaces release];
	[mapView release];
	[locationManager release];
	[mapViewCurrentLocationAnnotTitle release];
	[mapViewStoreLocationAnnotTitle release];	
    [super dealloc];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[self setTitle:@"Stores' Locations"];

/*	UIBarButtonItem     *addButton = [[UIBarButtonItem alloc] init];
	[addButton setTitle:@"List view"];
	self.navigationItem.rightBarButtonItem = addButton;
	self.navigationItem.leftBarButtonItem.enabled = YES;
	self.navigationItem.rightBarButtonItem.target=self;	
	self.navigationItem.rightBarButtonItem.action=@selector(switchToListView); */
	
	[self initLocationManager];
    [super viewDidLoad];
}

- (void) initLocationManager{
	CLLocationManager *locMan = [[CLLocationManager alloc] init];
	[locMan setDelegate:self];
	[locMan setDistanceFilter:10.0f];
	[locMan setDesiredAccuracy:kCLLocationAccuracyBest];
	[self setLocationManager:locMan];
	[locMan release];	
	// Once configured, the location manager must be "started".
	if ([self alternativeLocationCoordinate].latitude!=0 && [self alternativeLocationCoordinate].longitude!=0){
		[[self mapView] setShowsUserLocation:NO];
		[self dropThePins:[self alternativeLocationCoordinate]];
	}
	else
	{
		[[self mapView] setShowsUserLocation:YES];
		[[self locationManager] startUpdatingLocation];	
	}
}

#pragma mark methods

- (void) dropThePins: (CLLocationCoordinate2D) cd{
	[self setCurrentLocationCoordinate:cd];
	[self dropPinToCurrentLocation: cd];
	double rightest=cd.latitude;
	double leftest=cd.latitude;
	double toppest=cd.longitude;
	double bottomest=cd.longitude;
	
	for(int i=0; i<[[self foundPlaces] count];i++){
		Store * store  = [[self foundPlaces] objectAtIndex:i];
		cd.latitude=[store latitude];
		cd.longitude=[store longtitude];
		if (cd.latitude<=leftest)
			leftest=cd.latitude;
		else if (cd.latitude>rightest)
			rightest=cd.latitude;
		if (cd.longitude<=bottomest)
			bottomest=cd.longitude;
		else if (cd.longitude>toppest)
			toppest=cd.longitude;			
//		[store release];
		[self dropPinToCurrentLocation: cd];
	}	
	[self createRegion:leftest:rightest:toppest:bottomest];
}

-(void) nevigateToListView{
//		StoreListViewController *storeListViewController= [[StoreListViewController alloc] initWithNibName:@"StoreListViewController" bundle:nil];
/*		[storeListViewController setSearchProps:searchProps];
		[[self navigationController]pushViewController:storeListViewController animated:YES];
		[storeListViewController release];					*/
}

#pragma mark actions
- (IBAction) switchToListView{
	[self nevigateToListView];
}

#pragma mark actions

- (IBAction)reverseGeocodeCurrentLocation{
	/*    self.reverseGeocoder =
	 [[[MKReverseGeocoder alloc] initWithCoordinate:mapView.userLocation.location.coordinate] autorelease];
	 reverseGeocoder.delegate = self;
	 [reverseGeocoder start];	*/
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark mapDelegates

- (MKAnnotationView *)mapView:(MKMapView *)mapViewa viewForAnnotation:(id <MKAnnotation>)annotation {
	NSLog(@">> viewForAnnotation");
	
	// if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
		return nil;
	}
	
	
	// if this is annoation is a system annotation
	if ([annotation isKindOfClass:[SystemAnnotation class]]) {
		
		// try to dequeue an existing pin view first
        static NSString *SystemAnnotationIdentifier = @"SystemAnnotationIdentifier";
        MKPinAnnotationView *oldPinAnnotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:SystemAnnotationIdentifier];
		
		// if an existing pin view was not available
		if (!oldPinAnnotationView) {
			
			// create one
			MKPinAnnotationView *pinAnnotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:SystemAnnotationIdentifier];
			if ([annotation title] == mapViewCurrentLocationAnnotTitle )
				[pinAnnotationView setPinColor: mapViewCurrentLocColor];			
			else {
				[pinAnnotationView setPinColor: mapViewStoreLocColor];							
			}
			
			[pinAnnotationView setCanShowCallout:YES];
			[pinAnnotationView setSelected:YES];
			[pinAnnotationView setAnimatesDrop:YES];
			
			//			UIButton *rightAccessoryButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
			//			[rightAccessoryButton addTarget:self action:@selector(rightAccessoryAddButtonClicked) forControlEvents:UIControlEventTouchUpInside];			 			
			//			[pinAnnotationView setRightCalloutAccessoryView:rightAccessoryButton];
			// return the new pinannotationview
			return pinAnnotationView;
			
		} else { // if there is an old pin
			
			// assign the annotation to the old pinview
			[oldPinAnnotationView setAnnotation:annotation];
			
			// return the old pinannotationview
			return oldPinAnnotationView;
		}
		
	}
	
	return nil;
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views{
    // we have received our current location, so enable the "Get Current Address" button
	//    [getAddressButton setEnabled:YES];	
/*	for(MKAnnotationView *annotationView in views) {
		if(annotationView.annotation == mapView.userLocation) {
			MKCoordinateRegion newRegion=[self mapRegion];
			// zoom to this location
			if (newRegion.center.latitude!=0 && newRegion.center.longitude!=0 )
				[mapView setRegion:newRegion animated:YES];
			
			//[self performSelector:@selector(dropPinToCurrentLocation) withObject:nil afterDelay:1.0];
			//			[storeLoc release];
		}
	} */
}

- (void) createRegion: (double) leftest: (double) rightest: (double) toppest: (double) bottomest{
	
	CLLocationCoordinate2D location;	
	double latDelta=rightest-leftest;
	double longDelta=toppest-bottomest;	
	if (latDelta==0)
		latDelta=0.01;
	if (longDelta==0)
		longDelta=0.01;
	location.latitude=(double)(leftest+rightest)/2;
	location.longitude=(double)(toppest+bottomest)/2;
	if (location.longitude==0)
		location.longitude=leftest;
	if (location.longitude==0)
		location.longitude=toppest;
	
	MKCoordinateRegion newRegion;
	newRegion.center = location;
	newRegion.span.latitudeDelta = latDelta+(latDelta*0.1);
	newRegion.span.longitudeDelta =longDelta+(longDelta*0.1); 	
	[mapView setRegion:newRegion animated:YES];	
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
	NSLog(@"calloutAccessoryControlTapped");
}

#pragma mark locationDelegates
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	NSLog(@"didUpdateToLocation2");	
	[manager stopUpdatingLocation];
	CLLocationCoordinate2D cd=[[[self mapView] userLocation] coordinate];
	[self dropThePins:cd];	
}	

#pragma mark rgeocoderDelegate
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
	NSLog(@"didFindPlacemark");
	NSMutableString *locationAddress = [[NSMutableString alloc] init];
	
	if ([[placemark subThoroughfare] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.subThoroughfare];
	}
	
	if ([[placemark thoroughfare] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.thoroughfare];
	}
	
	if ([[placemark subLocality] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.subLocality];
	}
	
	if ([[placemark locality] length] > 0) {
		[locationAddress appendFormat:@"%@ ", placemark.locality];
	}
	// create a new annotation
	SystemAnnotation *systemAnnotation = [[SystemAnnotation alloc] init];
	if ([self areTheSamePlace: [placemark coordinate]: [self currentLocationCoordinate]])
		[systemAnnotation setAnnotationTitle: mapViewCurrentLocationAnnotTitle];					
	else
		[systemAnnotation setAnnotationTitle:mapViewStoreLocationAnnotTitle];							
	[systemAnnotation setAnnotationSubtitle:[NSString stringWithString:locationAddress]];
	//	[systemAnnotation setAnnotationCoordinate:[[[self mapView] userLocation] coordinate]];
	[systemAnnotation setAnnotationCoordinate:[placemark coordinate]];
	// add this annotation to the map
	[[self mapView] addAnnotation:systemAnnotation];
	[systemAnnotation release];
	// release string
	[locationAddress release];	
}

#pragma mark methods
- (void)dropPinToCurrentLocation: (CLLocationCoordinate2D) coordinate {
	//	MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[[[self mapView] userLocation] coordinate]];
	MKReverseGeocoder *reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate: coordinate];
	[reverseGeocoder setDelegate:self];
	[reverseGeocoder start];	
	/*	CLLocationCoordinate2D stCoorditane;
	 stCoorditane.latitude=[[self store]latitude];
	 stCoorditane.longitude=[[self store]longtitude];
	 reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:stCoorditane]; 
	 [reverseGeocoder setDelegate:self];
	 [reverseGeocoder start];	 */
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{	
    NSLog(@"MKReverseGeocoder has failed.");	
}

- (BOOL) areTheSamePlace: (CLLocationCoordinate2D) co1: (CLLocationCoordinate2D) co2{
	if (co1.latitude==co2.latitude && co1.longitude==co2.longitude )
		return YES;
	return NO;
}

@end
